package com.sddongyun.proxy;

import com.alibaba.fastjson.JSONObject;
import com.sddongyun.common.JaxWsDynamicClientFactory;
import com.sddongyun.common.utils.WJqueryUtils;
import com.sddongyun.config.ProxConfig;
import com.sddongyun.config.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by lenovo on 2019-11-30.
 */
@Slf4j
public class HisQueryProxyServlet extends ProxyServlet{

    JaxWsDynamicClientFactory clientFactory= JaxWsDynamicClientFactory.newInstance();

    private static final String URI = "uri";

    Client client;
    //在一个方法中连续调用多次WebService接口，每次调用前需要重置上下文。
    static ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Pattern pattern = Pattern.compile("<TradeCode>.*?</TradeCode>");

    @Override
    public void init() throws ServletException {
        Thread.currentThread().setContextClassLoader(classLoader);//在获取连接之前 还原上下文

        targetUri = getConfigParam(P_TARGET_URI);
        client=clientFactory.createClient(targetUri);

        HTTPConduit conduit=(HTTPConduit)client.getConduit();
        HTTPClientPolicy policy=new HTTPClientPolicy();
        policy.setConnectionTimeout(30000);
        policy.setReceiveTimeout(30000);
        policy.setConnectionRequestTimeout(30000);
        conduit.setClient(policy);
    }

    @Override
    protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException {

        String methodName=servletRequest.getParameter("soap_method");
        String input = servletRequest.getParameter("input");
        //RequestCode  RequestXML
        String RequestCode=servletRequest.getParameter("RequestCode");
        String RequestXML=servletRequest.getParameter("RequestXML");

//        input = "<Request><TradeCode>90008</TradeCode><Alias>amxl</Alias></Request>";
//        methodName = "GetMedPrice";
//        RequestCode = "90008";

        Matcher matcher = pattern.matcher(input);
        String reqCode = "";
        if (matcher.find()) {
            reqCode = matcher.group(0).toString();
        }

        log.info("targetUri: "+ targetUri);
        log.info("输入：methodName: "+methodName );
        log.info("输入：input: "+input );
        log.info("输入：RequestCode: "+reqCode );
        log.info("输入：RequestXML: "+RequestXML );
        JSONObject endJson = new JSONObject();
        endJson.put(URI, servletRequest.getRequestURI());


        endJson.put("reqDate", formatDate(new Date()));
        endJson.put("reqCode", reqCode);
        endJson.put("hisMehtod", methodName);
        endJson.put("parameter", input);
        try {
            Object[] response=null;
            //如果返回的address不是远程服务地址，重新制定地址
            client.getEndpoint().getEndpointInfo().setAddress(targetUri.replace("?wsdl",""));
            response= client.invoke(methodName,input);
            String out = response[0].toString();

//            String out = WJqueryUtils.queryWJ(methodName, input);

            servletResponse.getOutputStream().write(out.getBytes("utf-8"));
            log.info("输出："+out);
            endJson.put("resStr", out);
            endJson.put("resDate", formatDate(new Date()));
//            servletResponse.setCharacterEncoding("utf-8");
//            servletResponse.getWriter().write(response[0].toString());
        } catch (Exception e) {
            e.printStackTrace();
            endJson.put("resStr", e.getMessage());
            endJson.put("resDate", formatDate(new Date()));
        }

        JdbcTemplate jdbcTemplate = (JdbcTemplate)SpringContext.getBean("jdbcTemplate");
        jdbcTemplate.update(
                "insert into hisserverlog(serverip,url,reqdate,hismethod,reqcode,reqparams,resstr,resdate) VALUES (?,?,?,?,?,?,?,?)",
                "192.168.96.118",
                targetUri,
                endJson.get("reqDate").toString(),
                endJson.get("hisMehtod").toString(),
                endJson.get("reqCode").toString(),
                endJson.get("parameter").toString(),
                endJson.get("resStr").toString(),
                endJson.get("resDate").toString()
        );
    }

    public String formatDate(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }

    @Override
    public void destroy() {
        client.destroy();
    }
}
